<template>
  <div class="app-container">
    <div class="flex flex-items-start flex-justify-between pb-2px">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <div>
          <el-form-item prop="username">
            <el-input v-model="searchData.keyword" :placeholder="$t('shop.请输入商品信息') + '...'" clearable />
          </el-form-item>
          <el-form-item prop="phone">
            <!-- <el-date-picker v-model="timeValue" prefix-icon="" type="daterange" :range-separator="$t('common.至')"
              :start-placeholder="$t('common.开始时间')" :end-placeholder="$t('common.结束时间')" format="YYYY/MM/DD"
              value-format="YYYY-MM-DD" /> -->
              <el-date-picker
        v-model="timeValue"
         :range-separator="$t('common.至')"
        type="datetimerange"
        :start-placeholder="$t('common.开始时间')"
        :end-placeholder="$t('common.结束时间')"
        format="YYYY-MM-DD HH:mm:ss"
        value-format="YYYY-MM-DD HH:mm:ss"
      />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" round :icon="Search" @click="handleSearch">
              {{ $t('common.搜索') }}
            </el-button>
          </el-form-item>
        </div>
      </el-form>
      <div>
        <el-button type="info" round class="info-self-btn color-#4E5969" @click="handleDelete('')">
          {{ $t('shop.批量删除') }}
        </el-button>
      </div>
    </div>

    <div class="table-wrapper" v-loading="loading">
      <el-table :data="tableData" fixed="left" header-cell-class-name="cell-self-clas" cell-class-name="cell-class-name"
        :row-class-name="tableRowClassName" :row-key="getRowKey" size="large" border
        @selection-change="handleSelectionChange" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
        <el-table-column type="selection" width="55px" :selectable="hasSelectable"></el-table-column>
        <el-table-column prop="pic" :label="$t('shop.商品信息')" align="center" fixed min-width="280px">
          <template #default="{ row }">
            <div class="w100 flex flex-content-center flex-items-center shop_wrap">
              <el-image class="w-97px h-76px rounded-10px mr-8px flex-none" :src="row.pic" fit="fill"
                :preview-src-list="[row.pic]" preview-teleported></el-image>
              <div class="flex-1 text-align-left title">{{ row[CL('name')] || "--" }}</div>
            </div>

          </template>
        </el-table-column>
        <el-table-column :prop="CL('sell_price')" :label="$t('shop.单价')" align="center" min-width="140px">
          <template #default="{ row }">
            {{ $t('common.￥') }}{{ row[CL('sell_price')] }}
          </template>
        </el-table-column>
        <el-table-column prop="stock" :label="$t('shop.总库存')" align="center" min-width="84px">
          <template #default="{ row }">
            {{ row.stock }}{{ $t('shop.件') }}
          </template>
        </el-table-column>
        <el-table-column prop="createtime" :label="$t('shop.创建时间')" align="center" min-width="170px"> </el-table-column>
        <el-table-column :prop="CL('params')" :label="$t('shop.商品规格')" align="center"
          min-width="100px"></el-table-column>
        <el-table-column :prop="CL('pro_color')" :label="$t('shop.商品颜色')" align="center"
          min-width="110px"></el-table-column>
        <el-table-column fixed="right" :label="$t('common.操作')" width="180px" align="center">
          <template #default="{ row }">
            <div class="w100% flex flex-justify-around flex-items-center flex-wrap pb3px" v-if="!row.proid">
              <el-button type="primary" round class="mb12px primary-self-btn common_btn" @click="handleSetUp(row)">
                {{ $t('shop.重新上架') }}
              </el-button>
              <el-button type="info" round class="info-self-btn common_btn" @click="handleDelete(row)">
                {{ $t('shop.删除') }}
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pager-wrapper mt-10px">
      <el-pagination :layout="paginationData.layout" :page-sizes="paginationData.pageSizes"
        :total="paginationData.total" :page-size="paginationData.pageSize" :current-page="paginationData.currentPage"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>

  </div>
</template>


<script lang="ts" setup>
import type { resGoodData } from "@@/apis/good/type"
import { anchorEmits, type FormInstance } from "element-plus"
const router = useRouter()

import { getproductList, updateActivity, topUp, setst, delProduct } from "@@/apis/good"
import { usePagination } from "@@/composables/usePagination"
import { Search } from "@element-plus/icons-vue"
import type { TableColumnCtx } from 'element-plus'

import { inject, getCurrentInstance, ComponentInternalInstance } from 'vue'

import { useI18n } from 'vue-i18n';
const { locale, t } = useI18n();//登录国籍
const CL: any = inject("$CL");

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

defineOptions({
  // 命名当前组件
  name: "GoodList"
})
const lang = ref<string>("");
const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()


// #region 查
const tableData = ref<resGoodData[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const timeValue = ref<Array<string>>([])
const searchData = reactive({
  ctime: '',
  keyword: '',
})

watch(() => timeValue.value, (val) => {
  if(val){
  searchData.ctime = val.join(' ~ ')
  }else{
    searchData.ctime=''
  }
})

function getTableData() {
  loading.value = true
  let obj={
    page: paginationData.currentPage,
    limit: paginationData.pageSize,
    ctime: searchData.ctime,
    keyword: searchData.keyword,
    status: "0",
    gid: "",
  }
  let list=['keyword']
  if(locale.value=='ru'){
          for (let key in obj) {
            list.forEach((item=>{
              if (key === item) {
                obj[key + '_ru'] = obj[key]; // 将值赋给新 key
                delete obj[key];     // 删除旧的 key
              }
            }))
          }
  }
  getproductList(obj).then(({ data }) => {
    paginationData.total = data.count
    tableData.value = data.list;
  }).catch(() => {
    tableData.value = []
  }).finally(() => {
    loading.value = false
  })
}
function handleSearch() {
  paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
}

function getRowKey(row: any) {
  if (row.proid) {
    return (row.proid + "" + row.id);
  } else {
    return (row.id + "first");
  }
}

function hasSelectable(row: any, index: number) {
  return !row.proid;
}

// #endregion

// #region 编辑

// 商品上架
const handleSetUp = (row: any) => {
  router.push({ path: '/good/add-good', query: { id: (row as { id: string | number }).id, state:'3' } })
  // if (selectionList.value.length === 0 && !row) {
  //   ElMessage.warning(proxy!.$t('shop.请选择要上架的商品'))
  //   return;
  // }
  // let ids: Array<Number | String> = [];
  // if (!row) {
  //   toRaw(selectionList.value).forEach((ele) => {
  //     ids.push(ele.id);
  //   })
  // } else {
  //   ids = [row.id]
  // }

  // ElMessageBox.confirm(proxy!.$t('shop.确认上架商品吗？'), proxy!.$t('shop.上架商品'), {
  //   confirmButtonText: proxy!.$t('common.确认'),
  //   cancelButtonText: proxy!.$t('common.取消'),
  //   customClass: "new_box",
  //   type: "warning"
  // }).then(() => {
  //   setst({
  //     bid: row.bid,
  //     status: "1",
  //     ids: ids.join(','),
  //   }).then(() => {
  //     ElMessage.success("上架成功")
  //     getTableData()
  //   })
  // }).catch(() => {

  // })
}

// 列表选择
const selectionList = ref<{ id: number }[]>([])

// 删除
function handleDelete(row: any) {
  if (selectionList.value.length === 0 && !row) {
    ElMessage.warning(proxy!.$t('shop.请选择要删除的商品'))
    return;
  }
  ElMessageBox.confirm(proxy!.$t('shop.确认删除商品吗？'), proxy!.$t('shop.删除商品'), {
    confirmButtonText: proxy!.$t('common.确认'),
    cancelButtonText: proxy!.$t('common.取消'),
    customClass: "new_box",
    type: "warning"
  }).then(() => {
    let ids: Array<Number | String> = [];
    if (!row) {
      toRaw(selectionList.value).forEach((ele) => {
        ids.push(ele.id);
      })
    } else {
      ids = [row.id]
    }
    delProduct({
      bid: row.bid,
      ids: ids.join(','),
    }).then(() => {
      ElMessage.success(t('common.删除成功'))
      getTableData()
    })
  }).catch(() => {

  })
}

const handleSelectionChange = (e: { id: number }[]) => {
  selectionList.value = e;
}
// #endregion

// 表格隔行变色
interface User {
  date: string
  name: string
  address: string
}
const tableRowClassName = ({
  row,
  rowIndex,
}: {
  row: User
  rowIndex: number
}) => {
  if (rowIndex % 2 == 0) {
    return 'primary-row-color'
  } else {
    return 'info-row-color'
  }
}

// 监听分页参数的变化
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
</script>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;

  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}

.app-container {
  display: flex;
  flex-direction: column;
  overflow: hidden;

  // 筛选项重置
  .el-form {
    .el-form-item {

      :deep(.el-form-item__content) {
        .el-date-editor {
          border-radius: 16px;
          background: #F2F3F5;
          box-shadow: 0px 2px 2px 0px rgba(45, 45, 45, 0.10);
        }
      }

      .el-input {
        :deep(.el-input__wrapper) {
          border-radius: 16px;
          box-shadow: 0px 2px 2px 0px rgba(45, 45, 45, 0.10);
          background: #F2F3F5;
        }

      }
    }

  }

  .el-select {
    :deep(.el-select__wrapper) {
      border-radius: 16px;
      background: #007AFF;

      .el-select__placeholder {
        color: #fff;
      }

      .el-select__suffix {
        .el-icon {
          color: #fff;
        }
      }
    }
  }

  .table-wrapper {
    flex: 1;
    overflow: hidden;

    .el-table {
      height: 100%;
      border-top-left-radius: 30px;
      border-top-right-radius: 30px;

      :deep(.cell-self-clas) {
        color: #1D2129 !important;
        font-size: 14px;
        font-weight: 400;
        background: #F2F3F5;
        border-right: none;
      }

      :deep(.cell-class-name) {
        color: #1D2129 !important;
        font-size: 14px;
        font-weight: 400;
      }
    }

  }

  .order-wrapper {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 50px;

    .left-text {
      color: #1D2129;
      font-size: 14px;
      font-weight: 400;
    }
  }
}

:deep(.dialog-wrapppx) {
  background: linear-gradient(to right, #FBFCFD, #F5F9FD, #ECF6FD);
}

.info-self-btn {
  background: #F2F3F5;
  box-shadow: 0px 2px 2px 0px rgba(45, 45, 45, 0.10);
  color: #1D2129;
  border-color: transparent;
  &:hover {
    box-shadow: 0px 2px 2px 0px rgba(45, 45, 45, 0.3);
    transition: all 0.3s;
  }
}

:deep(.el-table .cell) {
  display: flex;
  align-items: center;
  justify-content: center;
}

.my-el-input-number {
  position: relative;
}

.my-el-input-number::after {
  content: '%';
  display: inline-block;
  height: 20px;
  line-height: 20px;
  width: 20px;
  text-align: center;
  position: absolute;
  right: 32px;
  top: 50%;
  font-size: 12px;
  transform: translateY(-50%);
}

.my-el-input-number .el-input__inner {
  padding-left: 30px;
  padding-right: 48px;
}

.common_btn {
  margin-left: 0;
  min-width: 70%;
}
</style>
